<template>
  <div class="edu-page-warp">
    <ConditionCard shadow="never" body-style="padding: 24px 24px 6px 24px;" @search="onSubmit"
      @reset="reset('queryForm')">
      <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="135px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item :label="$t('graduationList.graduationYear') + ':'" prop="graduationDate">
              <el-date-picker v-model="queryForm.graduationDate" value-format="yyyy" align="right" type="year"
                @change="graduationDateChange" :placeholder="$t('common.pla.pleaseSelect')"  style="width: 100%" :clearable="false" :editable="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.college') + ':'" prop="faculty">
              <el-select v-model="queryForm.faculty" style="width: 100%;" :filterable='role != 3' :clearable='role !=3'
                @change="getMajorOptions">
                <el-option v-for="item in options.faculty" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item filterable :label="$t('label.major') + ':'" prop="profession">
              <el-select v-model="queryForm.profession" @change="changeProfession" filterable clearable
                style="width: 100%">
                <el-option v-for="item in options.profession" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('auditStandard.proDirection') + ':'" prop="directionCode">
              <el-select v-model="queryForm.directionCode" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.direction" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item filterable :label="$t('graduationList.studentID')+ ':'" prop="name">
              <el-input v-model="queryForm.name" :placeholder="$t('common.pla.pleaseInput')" maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item filterable :label="$t('graduationList.machineReviewConclusion') + ':'"
              prop="machineConclusion">
              <el-select v-model="queryForm.machineConclusion" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.machineConclusion" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ConditionCard>
    <el-card v-loading="loading" shadow="never" body-style="padding: 24px;" class="card-margin collage-content">
      <div class="div-main clearfix">
        <div class="float-right">
          <el-button @click="exportAuditresult" type="primary">导出机审结果表</el-button>
          <el-button @click="setMachineFn" type="primary">
            机审
          </el-button>
        </div>
      </div>
      <EduTable :data="tableData" @page-change="handleCurrentChange" @selection-change="handleSelectionChange"
        :total="page.total" :pageSize="page.pageSize_" :page-num="page.pageNum_" :orderFixed="fixed"
        :selectFixed="fixed" :cellClassName="preline">
         <el-table-column :label="$t('graduationList.studentID')" prop="studentId" fixed="left"  width='80'></el-table-column>
        <el-table-column :label="$t('graduationList.name')" prop="name" fixed="left"  min-width='70'></el-table-column>
        <el-table-column :label="$t('graduationList.machineReviewConclusion')" prop="machineConclusionI18n" min-width='70'>
        </el-table-column>
        <el-table-column :label="$t('graduationList.machineReviewNotes')" width="280">
          <template slot-scope="scope">
            <div v-html="scope.row.machineRemark"></div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('graduationList.details')" min-width="280">
          <template slot-scope="scope">
            <div v-html="scope.row.machineDetails"></div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('graduationList.failingCourse')" prop="noPassCourse" min-width="120">
        </el-table-column>
        <el-table-column :label="$t('graduationList.machineReviewTime')" prop="machineDate" width="155">
        </el-table-column>
        <el-table-column :label="$t('graduationList.gradePoint')" prop="scorePoint" width="80"></el-table-column>
        <el-table-column :label="$t('graduationList.operating')" width="45" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.machineConclusionI18n" type="text" @click.stop="preview(scope.row)" size="mini">
              {{$t('graduationList.preview')}}
            </el-button>
          </template>
        </el-table-column>
      </EduTable>
      <edu-dialog :title="dialog.title" size="small" :visible.sync="dialog.show" :autoHeight="false"
        :confirmBtnText="$t('common.btn.confirm')" :close-on-click-modal="false" @close="close"
        @confirm="confirm('exportForm')">
        <el-form :model="dialog.formInfo" ref="exportForm" :rules="dialog.rules" label-width="120px"
          label-position="right" size="small">
          <el-row>
            <el-col :span="17">
              <el-form-item :label="$t('graduationList.graduationYear') + ':'" prop="graduationDate">
                <el-date-picker v-model="dialog.formInfo.graduationDate" type="year" style="width:100%"
                  value-format="yyyy" @change="dialogGraduateChange" :placeholder="$t('graduationList.pleaseSelect')">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="17">
              <el-form-item :label="$t('label.college') + ':'" prop="faculty">
                <el-select v-model="dialog.formInfo.faculty" @change="dialogFacultyChange" filterable clearable
                  style="width: 100%">
                  <el-option v-for="item in dialog.options.faculty" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="17">
              <el-form-item :label="$t('label.major') + ':'" prop="profession">
                <el-select v-model="dialog.formInfo.profession" filterable clearable style="width: 100%">
                  <el-option v-for="item in dialog.options.profession" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="17">
              <el-form-item :label="$t('graduationList.auditBatch') + ':'" prop="reviewBatch">
                <el-select v-model="dialog.formInfo.reviewBatch" style="width: 100%">
                  <el-option v-for="item in dialog.options.reviewBatch" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </edu-dialog>
    </el-card>
  </div>
</template>
<script>
  import Bus from "common/src/utils/bus";
  import UTILS from "common/src/utils/utils";
  import {
    queryDic
  } from "common/src/api/dictionary";
//   import {
//     findFaculty
//   } from "common/src/api/faculty";
  import {
    findGraduateList,
    setMachine,
    getRedisResult,
    findAllGraduateReviewBatch,
    findFaculty
  } from 'common/src/api/graduationManagement/graduationList'
  import manageApi from 'common/src/api/graduationManagement/graduationManage';
  import {getPower} from "common/src/api/culture/culturePlan";
  export default {
    name: "graduationQualificationAudit",
    data() {
      let currentYear = new Date().getFullYear();
      return {
        // 筛选相关选项
        queryForm: {
          graduationDate: currentYear + '',
          faculty: "",
          profession: "",
          directionCode: '',
          name: "",
          machineConclusion: '',
          isOverseas: "1"
        },
        page: {
          pageNum_: 1,
          pageSize_: 20,
          total: 0
        },
        fixed: true,
        // 下拉相关选项数据
        options: {
          faculty: [],
          profession: [],
          machineConclusion: [],
          direction: []
        },
        tableData: [],
        ids: [],
        preline: 'preline',
        role: '',
        dialog: {
          show: false,
          title: '',
          formInfo: {
            graduationDate: '',
            faculty: '',
            profession: '',
            reviewBatch: ''
          },
          options: {
            reviewBatch: [],
            profession: [],
            faculty: []
          },
          rules: {
            graduationDate: [{
              required: true,
              message: "请选择毕业年份",
              trigger: "change"
            }],
            faculty: [{
              required: true,
              message: "请选择学院",
              trigger: "change"
            }],
            profession: [{
              required: true,
              message: "请选择专业",
              trigger: "change"
            }],
            reviewBatch: [{
              required: true,
              message: "请选择审核批次",
              trigger: "change"
            }]
          }
        }
      };
    },
    created() {
      this.getRole();
    },
    methods: {
      init() {
        this.getMajorOptions(); 
        this.initOptions();
      },
      getRole() {
        getPower().then(res => {
            this.role = res.data.power;
            if (this.role == 4) {
              this.handleSearch();
            }
        }).finally(() => {
          this.init();
        });
      },
      initOptions() {
        this.getFacultyList('init');
        // findFaculty().then(res => {
        //   let data = {
        //     "X_YX": res.data
        //   };
        //   UTILS.fillSelect({
        //     faculty: "X_YX"
        //   }, data, this.options);
        //   if (this.role == 3) {
        //     this.queryForm.faculty = this.options.faculty[0] && this.options.faculty[0].value;  
        //     this.getMajorOptions();    
        //     this.handleSearch();
        //   }
        // });
        const data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: ["X_BYJL"]
        };
        queryDic(data).then(res => {
          if (res.code == 200) {
            UTILS.fillSelect({
                machineConclusion: "X_BYJL"
              },
              res.data,
              this.options
            );
          }
        });
      },
      graduationDateChange() {
          this.getFacultyList();
          this.getMajorOptions();
      },
      getFacultyList(type) {
        let param = {
            graduationDate: this.queryForm.graduationDate || '',
            isOverseas: this.queryForm.isOverseas
        };
        this.queryForm.faculty = '';
        this.getFaculty(this.options, param, type);
      },
      getDialogFaculty(){
        let param = {
            graduationDate: this.dialog.formInfo.graduationDate || '',
            isOverseas: this.queryForm.isOverseas
        };
        this.dialog.formInfo.faculty = '';
        this.getFaculty(this.dialog.options, param);
      },
      getFaculty(options, param, type) {
        options = options || {};
        options.faculty = [];
        findFaculty(param).then(res => {
            let data = {
                "X_YX": res.data
            };
            UTILS.fillSelect({
                faculty: "X_YX"
            }, data, options);
                if (this.role == 3 && type == "init") {
                    this.queryForm.faculty = this.options.faculty[0] && this.options.faculty[0].value;
                    this.getMajorOptions();
                    this.handleSearch();
                }
            });
      },
      initDirection() {
        this.options.direction = [];
        this.queryForm.directionCode = '';
        if (this.queryForm.profession) {
          let grade = this.professionMap && this.professionMap[this.queryForm.profession];
          let params = {
            pageNum_: 1,
            pageSize_: 20,
            grade: grade + '',
            professionCode: this.queryForm.profession
          };
          manageApi.findDirMaintenList(params).then(res => {
            if (res && res.code === 200) {
              let listData = res.data && res.data.list || [];
              let options = [];
              listData.forEach(item => {
                if (item.code) {
                  options.push({
                    key: item.code,
                    value: item.code,
                    label: item.name
                  })
                }
              })
              this.options.direction = options;
            }
          })
        }
      },
      changeProfession() {
        this.initDirection();
      },
      handleSearch() {
        this.checkList = [];
        let param = {
          ...this.queryForm,
          pageNum_: this.page.pageNum_,
          pageSize_: this.page.pageSize_
        }
        findGraduateList(param).then(res => {
          if (res.code == 200) {
            let data = res.data || [];
            let reg1 = /(;)?<br>$/g;
            let reg2 = /(;)?<br>;/g;
            (data.list || []).forEach(item =>{
              item.machineDetails = item.machineDetails && item.machineDetails.replace(reg1, '') || '';
              item.machineDetails = item.machineDetails.replace(reg2, ';<br>');
              item.machineRemark = item.machineRemark && item.machineRemark.replace(reg1, '') || '';
              item.machineRemark = item.machineRemark.replace(reg2, ';<br>');
            }) 
            this.tableData = data.list;
            this.page.pageNum_ = data.pageNum_;
            this.page.pageSize_ = data.pageSize_;
            this.page.total = data.total_;
          }
        }).catch(() => {
          this.tableData = [];
          this.page.pageNum_ = 1;
          this.page.pageSize_ = 20;
          this.page.total = 0;
        });
      },
      handleCurrentChange(val) {
        this.page.pageNum_ = val.pageNum;
        this.page.pageSize_ = val.pageSize;
        this.handleSearch();
      },
      getMajorOptions() {
        this.options.profession = [];
        this.queryForm.profession = "";
        this.options.direction = [];
        this.queryForm.directionCode = '';
        this.professionMap = {};
        if (!this.queryForm.graduationDate) {
          return;
        }
        manageApi.getProfessionByGrade({
            faculty: this.queryForm.faculty,
            graduateDate: this.queryForm.graduationDate,
          })
          .then(res => {
            if (res.code == 200) {
              let data = res.data || [];
              let profession = data.map((item, index) => {
                this.professionMap[item.professionCateGory] = item.grade;
                return {
                  label: item.professionCateGoryName + '-' + item.professionCateGory,
                  value: item.professionCateGory
                }
              })
              this.options.profession = _.uniqBy(profession, 'value');
            }
          });
      },
      onSubmit() {
        this.page.pageNum_ = 1;
        this.page.pageSize_ = 20;
        this.handleSearch();
      },
      reset(ref) {
        this.$refs[ref].resetFields();
        this.page.pageNum_ = 1;
        this.page.pageSize_ = 20;
        if (this.role == 3) {
          this.queryForm.faculty = this.options.faculty[0] && this.options.faculty[0].value;
        }
        this.getMajorOptions();
        this.options.direction = [];
        this.handleSearch();
      },
      handleSelectionChange(checksArr) {
        this.checkList = checksArr;
      },
      setMachineFn() {
        if (!this.queryForm.faculty) {
            this.$message({
                type: "warning",
                message: "请选择学院"
            });
            return;
        }
        let studentIdList = [];
        if (this.checkList && this.checkList.length) {
          this.checkList.forEach(item => {
            studentIdList.push(item.studentId);
          })
        }
        let data = {
          ...this.queryForm,
          studentIdList
        };
        let sleep = ms => {
          return new Promise(resolve => setTimeout(resolve, ms));
        };
        let loaded = false;
        let key = "";
        //重复发送请求，直到自动关联完成
        let delayRequest = async () => {
          if (loaded) {
            await sleep(5000);
          } else {
            loaded = true;
          }
          getRedisResult(key).then(response => {
            if (response.code == 200 && response.data.status) {
              this.$message({
                type: "success",
                message: "设置成功"
              });
              this.handleSearch();
            } else {
              const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(255, 255, 255, .48)"
              });
              delayRequest();
            }
          })
        };
        setMachine(data).then(response => {
          if (response.code === 200) {
            key = response.data.key;
            delayRequest();
          }
        });
      },
      preview(row) {
        this.$router.push({
          path: '/internationalGraduationManagement/internationGraduationQualificationAuditDetail',
          query: {
            studentId: row.studentId,
            currentPath: this.$route.path,
            queryForm:this.queryForm
          }
        })
      },
      exportAuditresult() {
        this.dialog.show = true;
        this.dialog.title = '导出机审结果表';
      },
      dialogFacultyChange() {
        this.getDialogMajor();
      },
      getDialogMajor() {
        this.dialog.formInfo.profession = '';
        if (!this.dialog.formInfo.graduationDate) {
          return;
        }
        manageApi.getProfessionByGrade({
          faculty: this.dialog.formInfo.faculty,
          graduateDate: this.dialog.formInfo.graduationDate,
        })
        .then(res => {
          if (res.code == 200) {
            let data = res.data || [];
            let profession = data.map((item, index) => {
              return {
                label: item.professionCateGoryName + '-' + item.professionCateGory,
                value: item.professionCateGory
              }
            })
            this.dialog.options.profession = _.uniqBy(profession, 'value');
          }
        });
      },
      dialogGraduateChange() {
        this.getDialogFaculty();
        this.dialog.formInfo.reviewBatch = '';
        this.dialog.formInfo.profession = '';
        this.dialog.options.reviewBatch = [];
        this.dialog.options.profession = [];
        if (!this.dialog.formInfo.graduationDate) {
          return;
        }
        this.getDialogMajor();
        findAllGraduateReviewBatch({
          isOverseas: this.queryForm.isOverseas,
          graduateData: this.dialog.formInfo.graduationDate
        })
        .then(res => {
          if (res.code == 200) {
            let batchs = [];
            batchs = (res.data && res.data.list || []).map((item, index) => {
              return {
                label: item.reviewBatchI18n,
                value: item.reviewBatch
              }
            });
            this.dialog.options.reviewBatch = [{
                value: "6",
                label: "全部"
              },
              {
                value: "0",
                label: "未审核"
              },
              ...batchs
            ]
          }
        });
      },
      close() {
        this.$refs.exportForm.resetFields();
        this.dialog.options.reviewBatch = [];
        this.dialog.options.profession = [];
      },
      confirm() {
        this.$refs.exportForm.validate(valid => {
          if (!valid) {
              return;
          }else {
            let params = {isOverseas: "1", ...this.dialog.formInfo};
            if (params.reviewBatch == 6) {
              params.reviewBatch = '';
            }
            window.location.href = `/api/graduationservice/graduateList/exportMachineConclusion?isOverseas=1&graduationDate=${params.graduationDate}&faculty=${params.faculty}&profession=${params.profession}&reviewBatch=${params.reviewBatch}`; 
            this.close();   
            this.dialog.show = false;                  
          }
        })
      }
    }
  };

</script>
<style lang="scss" scoped>
  .div-main {
    margin-bottom: 16px;
  }
    .collage-content ::v-deep .el-table{
        .cell, th div{
            padding-left: 5px;
            padding-right: 5px;
        }
    }
</style>
